<template>
  <div class="pdf-preview-component">
    <!-- PDF加载状态 -->
    <div v-if="loading" class="flex items-center justify-center" :style="{ height: containerHeight }">
      <a-spin size="large" tip="正在加载PDF..."/>
    </div>
    
    <!-- PDF内容区域 -->
    <div v-else-if="pdfUrl" class="pdf-content-container" :class="containerClass">
      <!-- PDF组件容器 -->
      <div class="relative" ref="pdfContainerRef">
        <!-- PDF组件 -->
        <vue-office-pdf
            :src="pdfUrl"
            @rendered="onPdfRendered"
            @error="onPdfError"
            @click="handlePdfClick"
            :class="computedPdfClass"
            :title="clickable ? '点击选择字段位置坐标' : undefined"
            :style="computedPdfStyle"
        />
        
        <!-- 坐标指示器 -->
        <div
            v-if="showIndicator && selectedPosition"
            class="absolute w-3 h-3 bg-red-500 border-2 border-white rounded-full transform -translate-x-1/2 -translate-y-1/2 z-20 pointer-events-none"
            :style="getIndicatorPosition()"
        ></div>
        
        <!-- 点击提示 -->
        <div v-if="clickable && showClickTip" class="absolute top-2 left-2 bg-blue-500 text-white px-2 py-1 rounded text-xs z-10">
          点击选择坐标位置
        </div>
      </div>
    </div>
    
    <!-- 无PDF内容 -->
    <div v-else class="flex flex-col items-center justify-center text-gray-500" :style="{ height: containerHeight }">
      <div>{{ emptyText }}</div>
      <!-- 调试信息 -->
      <div v-if="pdfUrl" class="mt-2 text-xs text-gray-400">
        PDF URL: {{ pdfUrl.substring(0, 50) }}{{ pdfUrl.length > 50 ? '...' : '' }}
      </div>
      <div v-if="!pdfUrl" class="mt-2 text-xs text-red-400">
        未提供PDF URL
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, computed, onUnmounted } from 'vue';
import VueOfficePdf from '@vue-office/pdf';
import { getCurrentInstance } from 'vue';

// 全局实例
const { proxy } = getCurrentInstance();

// 定义props
const props = defineProps({
  // PDF文件URL
  pdfUrl: {
    type: String,
    default: ''
  },
  // 是否可点击选择坐标
  clickable: {
    type: Boolean,
    default: false
  },
  // 是否显示分页控制
  showPagination: {
    type: Boolean,
    default: true
  },
  // 是否显示页码标识
  showPageNumber: {
    type: Boolean,
    default: false
  },
  // 是否显示点击提示
  showClickTip: {
    type: Boolean,
    default: false
  },
  // 是否显示坐标指示器
  showIndicator: {
    type: Boolean,
    default: false
  },
  // 选中的位置信息
  selectedPosition: {
    type: Object,
    default: null
  },
  // 初始页码（vue-office不支持分页，保留接口兼容性）
  initialPage: {
    type: Number,
    default: 1
  },
  // 容器高度
  containerHeight: {
    type: String,
    default: '600px'
  },
  // 空状态文本
  emptyText: {
    type: String,
    default: '暂无PDF内容'
  },
  // 容器样式类
  containerClass: {
    type: String,
    default: 'pdf-pages-container max-h-[600px] overflow-y-auto'
  },
  // 分页控制样式类
  paginationClass: {
    type: String,
    default: 'flex items-center justify-center mb-4 space-x-4'
  },
  // 分页按钮大小
  paginationSize: {
    type: String,
    default: 'small'
  },
  // 页码信息样式类
  pageInfoClass: {
    type: String,
    default: 'text-sm text-gray-600'
  },
  // PDF组件样式类
  pdfClass: {
    type: String,
    default: 'border border-gray-300'
  },
  // PDF组件样式
  pdfStyle: {
    type: Object,
    default: () => ({ display: 'block', margin: '0 auto', padding: '0' })
  },
  // 是否自动重新加载PDF
  autoReload: {
    type: Boolean,
    default: false
  }
});

// 定义emits
const emit = defineEmits([
  'loaded',
  'error',
  'progress',
  'click',
  'page-change',
  'position-select',
  'reload-request'
]);

// 响应式数据
const loading = ref(false);
const numPages = ref(1); // vue-office显示整个PDF，设为1页
const currentPage = ref(1); // vue-office不支持分页
const pdfContainerRef = ref(null);
const isReloadingPdf = ref(false);

// 计算属性
const computedPdfClass = computed(() => {
  let classes = props.pdfClass;
  if (props.clickable) {
    classes += ' cursor-crosshair';
  }
  return classes;
});

const computedPdfStyle = computed(() => {
  return {
    ...props.pdfStyle, // 原始样式
    width: '100%',    // 确保宽度为100%
    height: props.containerHeight, // 设置高度
    display: 'block', // 确保是块级元素
    ...(props.clickable && { cursor: 'crosshair' })
  };
});

// PDF相关函数
function onPdfRendered() {
  console.log('PDF渲染完成');
  
  // 清除加载超时
  if (window.pdfLoadingTimeout) {
    clearTimeout(window.pdfLoadingTimeout);
    window.pdfLoadingTimeout = null;
  }
  
  nextTick(() => {
    loading.value = false;
    isReloadingPdf.value = false;
    console.log('PDF加载状态已设置为false，重新加载标志已清除');
    emit('loaded', { message: 'PDF渲染完成' });
  });
}

function onPdfError(error) {
  console.error('PDF加载失败:', error);
  
  // 清除加载超时
  if (window.pdfLoadingTimeout) {
    clearTimeout(window.pdfLoadingTimeout);
    window.pdfLoadingTimeout = null;
  }
  
  loading.value = false;
  isReloadingPdf.value = false;
  emit('error', error);
  
  if (proxy) {
    proxy.$message.error('PDF加载失败，请检查文件是否有效');
  }
}

// 分页控制（vue-office不支持分页，保留接口兼容性）
function previousPage() {
  console.log('vue-office不支持分页控制');
  emit('page-change', 1);
}

function nextPage() {
  console.log('vue-office不支持分页控制');
  emit('page-change', 1);
}

// 处理PDF点击
function handlePdfClick(event) {
  if (!props.clickable) return;
  
  // 阻止事件冒泡
  event.stopPropagation();
  
  // 获取点击的PDF元素
  const pdfElement = event.target.closest('.vue-office-pdf') || event.target;
  if (!pdfElement) {
    console.warn('未找到PDF元素');
    return;
  }
  
  const rect = pdfElement.getBoundingClientRect();
  
  // 计算相对于PDF元素的坐标
  const x = Math.round(event.clientX - rect.left);
  const y = Math.round(event.clientY - rect.top);
  
  const position = {
    x: x,
    y: y,
    pageNumber: 1, // vue-office显示整个PDF，页码固定为1
    canvasX: x,
    canvasY: y
  };
  
  console.log(`PDF点击坐标: (${x}, ${y})`);
  
  emit('click', event);
  emit('position-select', position);
  
  // 显示坐标选择提示
  if (proxy) {
    proxy.$message.success(`坐标已设置: (${x}, ${y})`);
  }
}

// 获取指示器位置
function getIndicatorPosition() {
  if (!props.selectedPosition || !props.selectedPosition.x || !props.selectedPosition.y) {
    return { display: 'none' };
  }
  
  // 获取PDF元素
  const pdfElement = pdfContainerRef.value?.querySelector('.vue-office-pdf');
  if (!pdfElement) {
    return { display: 'none' };
  }
  
  const rect = pdfElement.getBoundingClientRect();
  const containerRect = pdfContainerRef.value.getBoundingClientRect();
  
  // 直接使用坐标位置
  const x = parseInt(props.selectedPosition.x);
  const y = parseInt(props.selectedPosition.y);
  
  // 相对于容器的位置
  const left = (rect.left - containerRect.left) + x;
  const top = (rect.top - containerRect.top) + y;
  
  return {
    left: left + 'px',
    top: top + 'px'
  };
}

// 强制重新加载PDF
function reloadPdf() {
  if (!props.pdfUrl) return;
  
  console.log('强制重新加载PDF');
  loading.value = true;
  isReloadingPdf.value = true;
  
  nextTick(() => {
    // 通过改变URL来触发重新加载
    const currentUrl = props.pdfUrl;
    // 这里需要父组件配合，暂时清空URL然后恢复
    emit('reload-request', currentUrl);
  });
}



// 监听PDF URL变化
watch(
  () => props.pdfUrl,
  (newUrl, oldUrl) => {
    console.log('PDF URL变化:', { newUrl, oldUrl });
    
    // 清除之前的超时
    if (window.pdfLoadingTimeout) {
      clearTimeout(window.pdfLoadingTimeout);
      window.pdfLoadingTimeout = null;
    }
    
    if (newUrl && newUrl !== oldUrl) {
      console.log('开始加载新PDF:', newUrl);
      loading.value = true;
      numPages.value = 0;
      currentPage.value = props.initialPage;
      
      // 验证URL格式
      try {
        new URL(newUrl);
      } catch (urlError) {
        console.error('无效的PDF URL:', newUrl);
        loading.value = false;
        if (proxy) {
          proxy.$message.error('无效的PDF URL格式');
        }
        emit('error', new Error('无效的PDF URL格式'));
        return;
      }
      
      // 添加超时处理，防止无限加载
      const loadingTimeout = setTimeout(() => {
        if (loading.value) {
          console.warn('PDF加载超时');
          loading.value = false;
          if (proxy) {
            proxy.$message.error('PDF加载超时，请检查网络连接或文件是否存在');
          }
          emit('error', new Error('PDF加载超时'));
        }
      }, 15000); // 减少到15秒超时
      
      window.pdfLoadingTimeout = loadingTimeout;
      
    } else if (!newUrl) {
      console.log('PDF URL为空，清除加载状态');
      loading.value = false;
      numPages.value = 0;
    }
  },
  { immediate: true }
);



// 组件卸载时清理
onUnmounted(() => {
  // 清除加载超时定时器
  if (window.pdfLoadingTimeout) {
    clearTimeout(window.pdfLoadingTimeout);
    window.pdfLoadingTimeout = null;
  }
});

// 暴露方法给父组件
defineExpose({
  reloadPdf,
  previousPage,
  nextPage,
  currentPage: () => 1, // vue-office不支持分页
  numPages: () => 1,    // vue-office显示整个PDF
  loading: () => loading.value
});
</script>

<style scoped>
.pdf-preview-component {
  width: 100%;
  height: 100%;
}

.pdf-content-container {
  position: relative;
  width: 100%; /* 确保内容容器宽度为100% */
  height: 100%; /* 确保内容容器高度为100% */
}

.pdf-pages-container {
  position: relative;
  width: 100%; /* 确保页面容器宽度为100% */
  height: 100%; /* 确保页面容器高度为100% */
  overflow: auto; /* 如果内容超出，则显示滚动条 */
}
</style>